import Taro, { Component, Config } from '@tarojs/taro'
import { Button, View, ScrollView, Input, Icon } from '@tarojs/components'
import './index.scss'
import { getOrderPage } from '@/api/orderApi'
import { ORDER_TYPE } from '@/config/types'
import { ListEmpty, LoadMore, TabList, OrderCardHead, OrderCardBody, TabBar, FyImg } from "@/components/index"
import { toWaitGroupPage, toOrderCommentPage, toOrderInfoPage, toServiceComplaint, toOrderUnpaidPage, toCommentListPage, toOrderVerificationPage } from "@/utils/page_router"
import CarouselTwo from "@/components/custom-layout/carousel-two";
import GoodsCategories from "@/components/custom-layout/goods-categories";
import { getCustomPage } from "@/api/pageApi";
import EmptySearch from '@/assets/images/empty-image-search.png'
import { USER_INFO } from "@/config/storage";
import ScrollTop from "@/components/scroll-top"

const tabList = [
  { title: '全部', val: '' },
  { title: '待付款', val: ORDER_TYPE.UNPAID },
  { title: '待发货', val: ORDER_TYPE.UN_SEND },
  { title: '待收货', val: ORDER_TYPE.SENDING },
  { title: '已完成', val: ORDER_TYPE.CLOSED },
]

const scroll: any = {}
const fun = function () { }
const info = Taro.getStorageSync(USER_INFO)
export default class Index extends Component {
  state: any
  config: Config = {
  }
  static options = {
    addGlobalClass: true
  }

  constructor() {
    super(...arguments)
    const { params } = this.$router
    this.state = {
      page: 1,
      limit: 2,
      orderList: [],
      loadStatus: 'loading',
      typeKey: isNaN(Number(params.status)) ? 0 : Number(params.status),
      typeList: tabList,
      telephone: info.telephone || undefined,
      carousel: {},
      goodsList: {},
      zhiding: false,
      duihuanbi: true,
    }
  }

  componentWillMount() {
    this.getOrderListPage()
    getCustomPage('goods_commend').then(({ data }) => {
      const Index = data.content.findIndex(item => item.key === 'goodsCategories')
      const carousel = data.content.findIndex(item => item.key === 'carousel')
      if (Index >= 0) {
        this.setState({
          goodsList: data.content[Index],
          carousel: data.content[carousel]
        })
      }
    })
  }

  //  切换订单类型
  onClickType(key) {
    this.setState({
      page: 1,
      typeKey: key,
      orderList: [],
      loadStatus: 'loading',
      telephone: undefined
    }, () => {
      setTimeout(() => {
        this.getOrderListPage()
      }, 500)
    })
  }

  // 订单搜索
  onConfirmSearch() {
    const { telephone } = this.state
    if (telephone && telephone.length < 10) {
      Taro.showToast({ title: '请输入正确的电话号码', icon: 'none' })
      return
    }
    this.setState({
      page: 1,
      orderList: [],
      loadStatus: 'loading',
    }, () => {
      setTimeout(() => {
        this.getOrderListPage()
      }, 500)
    })
  }

  //  input 输入 change 事件
  onInput(e) {
    this.setState({
      telephone: e.detail.value
    })
  }

  // 清空电话按钮
  onRemoveTelephone() {
    this.setState({
      page: 1,
      orderList: [],
      loadStatus: 'loading',
      telephone: undefined
    }, () => {
      setTimeout(() => {
        this.getOrderListPage()
      }, 500)
    })
  }

  //  获取订单列表数据
  getOrderListPage() {
    const { page, limit, typeKey, typeList, orderList, loadStatus, telephone } = this.state
    if (loadStatus === 'noMore') {
      return
    }
    getOrderPage({ page, limit, status: typeList[typeKey]['val'] || undefined, addressSnap: telephone || undefined }).then(res => {
      const { list, totalCount } = res.data
      this.setState({
        page: page + 1,
        orderList: page === 1 ? list : orderList.concat(list),
        loadStatus: (page * limit >= totalCount) ? 'noMore' : 'more',
      })
    })
  }
  // 查看更多
  loadMore() {
    this.setState({
      loadStatus: 'loading',
    })
    this.getOrderListPage()
  }

  onPageScroll(res: any) {
    scroll.onPageScroll && scroll.onPageScroll(res.scrollTop)
    if (res.scrollTop > 300) {
      this.setState({
        zhiding: true,
      })
    } else {
      this.setState({
        zhiding: false,
      })
    }
    if (res.scrollTop) {
      this.setState({
        duihuanbi: false,
      })
    } else {
      this.setState({
        duihuanbi: true,
      })
    }
  }

  onReachBottom() {
    scroll.onReachBottom && scroll.onReachBottom()
  }


  showDuihuanbi() {
    this.setState({
      duihuanbi: true
    })
  }

  render() {
    const { typeKey, typeList, orderList, loadStatus, telephone, carousel, goodsList, zhiding, duihuanbi }: any = this.state
    return (<View className='order-page'>
      <ScrollTop ref="ScrollTop" zhiding={zhiding} duihuanbi={duihuanbi} showDuihuanbi={this.showDuihuanbi.bind(this)} />
      <TabList list={typeList} current={typeKey} className='thin-border__b' onClick={this.onClickType.bind(this)} />
      <View className='d-f a-i-c'>
        <View className='input-box d-f j-c-b a-i-c'>
          <View className='bnn-icon search-icon'>&#xe65c;</View>
          <Input
            value={telephone}
            type='number'
            className='search-input'
            placeholder='请输入手机号，查询您的订单'
            onInput={this.onInput.bind(this)}
            onConfirm={this.onConfirmSearch.bind(this)} />
          {telephone && <Icon className="icon-small search-remove" type="cancel" size="16" onClick={this.onRemoveTelephone.bind(this)} />}
        </View>
        <View className='search-btn f-g-5' onClick={this.onConfirmSearch.bind(this)}>搜索</View>
      </View>
      <ScrollView scrollY className='list-body' onScrollToLower={this.getOrderListPage.bind(this)}>
        <View className='order-list'>
          {orderList.map(order => {
            return (<View key={order.id} className='order-item'>
              <OrderCardHead order={order} />
              <OrderCardBody order={order} onClick={order.status == ORDER_TYPE.PINKING ? () => toWaitGroupPage(order.id) : () => toOrderInfoPage(order.id)} />
              <View className='order-foot'>
                {
                  order.status == ORDER_TYPE.PINKING ? (
                    <Button className='order-btn xf-btn xf-btn-primary xf-btn-round' onClick={() => toWaitGroupPage(order.id)}>查看详情</Button>
                  ) : (
                    <Button className='order-btn xf-btn xf-btn-round' onClick={() => toServiceComplaint()}>联系客服</Button>
                  )
                }
                {order.status == ORDER_TYPE.UNPAID && <Button className='order-btn xf-btn xf-btn-danger xf-btn-round' onClick={() => toOrderUnpaidPage(order.id)}>去支付</Button>}
                {order.status == ORDER_TYPE.UN_CHECK && <Button className='order-btn xf-btn xf-btn-primary xf-btn-round' onClick={() => toOrderVerificationPage(order.id)}>电子凭证</Button>}
                {order.status == ORDER_TYPE.CLOSED && !!!order.isReply && <Button className='order-btn xf-btn xf-btn-danger xf-btn-round' onClick={() => toOrderCommentPage(order.id)}>评论</Button>}
                {order.status == ORDER_TYPE.CLOSED && !!order.isReply && <Button className='order-btn xf-btn xf-btn-round' onClick={() => toCommentListPage(order.id)}>查看评价</Button>}
              </View>
            </View>)
          })}
        </View>

        {/*{!orderList.length && loadStatus == 'noMore' ? (<ListEmpty className='empty'/>) : (<LoadMore status={loadStatus}/>)}*/}
        {!orderList.length && loadStatus == 'noMore' ? (
          <View className='empty-content'>
            <FyImg src={EmptySearch} className='empty-img' />
            <View>请输入手机号查询您的订单信息</View>
          </View>
        ) : (
          <View onClick={loadStatus == 'more' ? this.loadMore.bind(this) : fun} >
            <LoadMore status={loadStatus} />
          </View>
        )}
      </ScrollView>

      {carousel && <View className='carousel'>
        <CarouselTwo {...carousel} />
      </View>}
      {goodsList.list && <GoodsCategories {...goodsList} scroll={scroll} />}
      <TabBar />
    </View>)
  }
}
